package com.guofen.controller.sjq;

import com.guofen.pojo.SjqWaterProductionDeliverWater;
import com.guofen.service.sjq.SjqWaterProductionDeliverWaterService;
import com.guofen.util.result.Result;
import com.guofen.util.result.ResultGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/sjq/sjqWaterProductionDeliverWater")
@Controller
@Api(tags = "SjqWaterProductionDeliverWaterController", description = "水处理生产现场记录表（送水)")
public class SjqWaterProductionDeliverWaterController {
    @Autowired
    private SjqWaterProductionDeliverWaterService sjqWaterProductionDeliverWaterService;

    @ApiOperation("添加记录")
    @RequestMapping(value = "/addForm", method = RequestMethod.POST)
    @ResponseBody
    public Result addForm(@ApiParam(name = "train_number", value = "车次", required = true) @RequestParam String train_number,
                          @ApiParam(name = "weight", value = "净重", required = true) @RequestParam String weight,
                          @ApiParam(name = "deliver_person", value = "送水人", required = true) @RequestParam String deliver_person,
                          @ApiParam(name = "recording_person", value = "记录人", required = true) @RequestParam String recording_person,
                          @ApiParam(name = "remarks", value = "备注", required = false) @RequestParam String remarks){
        Integer train_number1 = Integer.parseInt(train_number);
        Double weight1 = Double.parseDouble(weight);
        if (sjqWaterProductionDeliverWaterService.addForm(train_number1, weight1, deliver_person, recording_person,  remarks))
            return ResultGenerator.genSuccessResult();
        else
            return ResultGenerator.genFailResult("保存失败");
    }

    @ApiOperation("EXCEL批量添加记录")
    @PostMapping("/addFromExcel")
    @ResponseBody
    public Result doRegisterFromExcel(@RequestParam("file") MultipartFile file){
        String EXCEL_XLS = "xls";
        String EXCEL_XLSX = "xlsx";

        if (file.isEmpty())
            return ResultGenerator.genFailResult("文件为空");
        System.out.println(file.getOriginalFilename());
        List<Boolean> registerResult = new ArrayList<>();

        try {
            //根据路径获取这个操作excel的实例
            Sheet sheet = null;
            Row row = null;
            if (file.getOriginalFilename().endsWith(EXCEL_XLS)) {
                HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
                sheet = wb.getSheetAt(0);
            } else if (file.getOriginalFilename().endsWith(EXCEL_XLSX)) {
                XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
                //根据页面index 获取sheet页
                sheet = wb.getSheetAt(0);
            }

            List<SjqWaterProductionDeliverWater> sjqWaterProductionDeliverWaters = new ArrayList<>();

            //循环sheet页中数据从第三行开始，第一行是导入说明，第二行是标题
            for (int i = 2; i < sheet.getPhysicalNumberOfRows(); i++) {
                //获取每一行数据
                row = sheet.getRow(i);
                //用于表格中空数据的处理,如果车次和垃圾重量为0，则此项数据不进行录入
                //如果表格中的除序号和备注外的项都为空，则也要删除该项数据
                if((row.getCell(1)==null&&row.getCell(2)==null&&row.getCell(3)==null
                        &&row.getCell(4)==null)||row.getCell(1).getNumericCellValue()==0
                        ||row.getCell(2).getNumericCellValue()==0){
                    continue;
                }
                SjqWaterProductionDeliverWater sjqWaterProductionDeliverWater = new SjqWaterProductionDeliverWater();
                if(row.getCell(0)!=null){
                    Cell cell = row.getCell(0);
                    cell.setCellType(CellType.STRING);
                    sjqWaterProductionDeliverWater.setDate(cell.getStringCellValue());
                }
                if(row.getCell(1)!=null){
                    sjqWaterProductionDeliverWater.setTrainNumber((int)row.getCell(1).getNumericCellValue());
                }
                if(row.getCell(2)!=null){
                    sjqWaterProductionDeliverWater.setWeight(row.getCell(2).getNumericCellValue());
                }
                if(row.getCell(3)!=null){
                    Cell cell = row.getCell(3);
                    cell.setCellType(CellType.STRING);
                    sjqWaterProductionDeliverWater.setDeliverPerson(cell.getStringCellValue());
                }
                if(row.getCell(4)!=null){
                    Cell cell = row.getCell(4);
                    cell.setCellType(CellType.STRING);
                    sjqWaterProductionDeliverWater.setRecordingPerson(cell.getStringCellValue());
                }
                if(row.getCell(5)!=null){
                    Cell cell = row.getCell(5);
                    cell.setCellType(CellType.STRING);
                    sjqWaterProductionDeliverWater.setRemarks(cell.getStringCellValue());
                }
                System.out.println(sjqWaterProductionDeliverWater.getTrainNumber());
                System.out.println(sjqWaterProductionDeliverWater.getDate());
                sjqWaterProductionDeliverWaters.add(sjqWaterProductionDeliverWater);
            }
            for (SjqWaterProductionDeliverWater u : sjqWaterProductionDeliverWaters) {
                Boolean test = false;
                registerResult.add(test = sjqWaterProductionDeliverWaterService.addFormExcel(u.getDate(),
                        u.getTrainNumber(),u.getWeight(),u.getDeliverPerson(),u.getRecordingPerson(),u.getRemarks()));
                System.out.println(test);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultGenerator.genSuccessResult(registerResult);
    }


    @ApiOperation("查询记录")
    @RequestMapping(value = "/findForm", method = RequestMethod.GET)
    @ResponseBody
    public Result findForm(){
        if (sjqWaterProductionDeliverWaterService.findForm() != null)
            return ResultGenerator.genSuccessResult(sjqWaterProductionDeliverWaterService.findForm());
        else
            return ResultGenerator.genFailResult("暂无记录");
    }


    @ApiOperation("删除记录")
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @ResponseBody
    public Result delete(@ApiParam(name="id",value="ID",required=true) @RequestParam Integer id) {
        return ResultGenerator.genSuccessResult(sjqWaterProductionDeliverWaterService.delete(id));
    }

    @ApiOperation("修改记录")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    public Result update(@ApiParam(name="id",value="ID",required=true) @RequestParam Integer id,
                         @ApiParam(name = "train_number", value = "车次", required = true) @RequestParam String train_number,
                         @ApiParam(name = "weight", value = "净重", required = true) @RequestParam String weight,
                         @ApiParam(name = "deliver_person", value = "送水人", required = true) @RequestParam String deliver_person,
                         @ApiParam(name = "recording_person", value = "记录人", required = true) @RequestParam String recording_person,
                         @ApiParam(name = "remarks", value = "备注", required = false) @RequestParam String remarks) {
        Integer train_number1 = Integer.parseInt(train_number);
        Double weight1 = Double.parseDouble(weight);
        SjqWaterProductionDeliverWater record = new SjqWaterProductionDeliverWater();
        record.setId(id);
        record.setTrainNumber(train_number1);
        record.setWeight(weight1);
        record.setDeliverPerson(deliver_person);
        record.setRecordingPerson(recording_person);
        record.setRemarks(remarks);
        return ResultGenerator.genSuccessResult(sjqWaterProductionDeliverWaterService.update(record));
    }

    @ApiOperation("查找记录")
    @RequestMapping(value = "/select",method = RequestMethod.POST)
    @ResponseBody
    public Result select(@ApiParam(name="pageSize",value="页容量",required=true) @RequestParam Integer pageSize,
                         @ApiParam(name="currentPage",value="当前页",required=true) @RequestParam Integer currentPage,
                         @ApiParam(name="startTime",value="开始时间") Long startTime,
                         @ApiParam(name="endTime",value="截止时间") Long endTime) {
        if (startTime == null || endTime == null)
            return ResultGenerator.genSuccessResult(sjqWaterProductionDeliverWaterService.get(pageSize, currentPage));
        else
            return ResultGenerator.genSuccessResult(sjqWaterProductionDeliverWaterService.getByTime(pageSize, currentPage, startTime, endTime));
    }
}
